package com.yxlgateway.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yxlcommon.common.mapper.DemandReceiveMapper;
import com.yxlcommon.common.mapper.OrdersMapper;
import com.yxlgateway.service.CallBackService;
import com.yxlgateway.service.OrdersService;
import com.yxlgateway.service.PayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author: yxl
 * @since: 2022-01-06
 **/
@Service
@Slf4j
public class CallBackServiceImpl implements CallBackService {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private PayService payService;

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private DemandReceiveMapper demandReceiveMapper;

    @Override
    public String callBack(HttpServletRequest httpRequest) {
        if (callInterFaceSuccess(httpRequest)){
            return "success";
        }else
        {
            return "fail";
        }
    }

    private synchronized boolean callInterFaceSuccess(HttpServletRequest httpRequest){
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = httpRequest.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, new String(valueStr.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
        }
        JSONObject body = JSONObject.parseObject(params.get("body"));
        JSONObject jsonObject = JSONObject.parseObject(body.toJSONString());
        Long orderId = payService.selectOrderId(params.get("out_trade_no"));
        Integer demandId = ordersMapper.selectDemandId(orderId);
        if (Objects.equals((byte) 1, jsonObject.getByte("type")) & "TRADE_SUCCESS".equals(params.get("trade_status"))){
            payService.updateOrderStatus(params.get("out_trade_no"));
            if (Objects.equals("定金", payService.searchSubject(params.get("out_trade_no")))){
                ordersMapper.updateStatus((byte) 2, orderId);
                demandReceiveMapper.updatePayStatus((byte) 1, demandId);
            } else {
                ordersMapper.updateStatus((byte) 4, orderId);
                ordersMapper.updatePayTime(orderId);
                demandReceiveMapper.updatePayStatus((byte) 2, demandId);
            }
        }
        return true;
    }
}
